import { Component, OnInit, AfterViewInit } from "@angular/core";
import { NavigationEnd, Router, ActivatedRoute } from "@angular/router";
import { Title } from "@angular/platform-browser";
import { filter, map, mergeMap } from "rxjs/operators";
import { registerMicroApps, start, addGlobalUncaughtErrorHandler } from "qiankun";
import { menuList } from "./common/menu";
import type { MenuProps } from "./types";
import { SpinService } from "./services/spin.service";
import { environment } from "src/environments/environment";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.less"]
})
export class AppComponent implements OnInit, AfterViewInit {
  $loading = this.spinService.getGlobalSpin();
  isCollapsed = false;
  menus: MenuProps[] = menuList;

  constructor(
    private spinService: SpinService,
    public router: Router,
    private currentRoute: ActivatedRoute,
    private docmentTitle: Title
  ) {}

  ngOnInit() {
    this.router.events
      .pipe(
        filter((event) => event instanceof NavigationEnd),
        map(() => this.currentRoute),
        map((route) => {
          while (route.firstChild) {
            route = route.firstChild;
          }
          return route;
        }),
        mergeMap((route) => {
          return route.data;
        })
      )
      .subscribe((route) => {
        this.spinService.setGlobalSpin(false);

        const currentDocmentTile = route.title ? `${route.title} - Angular Design Pro` : "Angular Design Pro";
        this.docmentTitle.setTitle(currentDocmentTile);
      });
  }

  ngAfterViewInit() {
    if (!(window as any).qiankunStarted) {
      (window as any).qiankunStarted = true;

      /**
       * 注册子应用入口
       */
      registerMicroApps(
        [
          {
            name: "angular9",
            entry: environment.production ? "/angular9-dist/angular9/" : "//localhost:9529",
            container: "#ng-container",
            activeRule: "#/portal/ng9",
            props: { ngRouter: this.router }
          },
          {
            name: "react-template-ts",
            entry: environment.production ? "/react18-dist/" : "//localhost:9528",
            container: "#react-container",
            activeRule: "#/portal/rc18",
            props: {
              basename: "/portal/rc18",
              token: "AEcE4861-ED9b-1eBD-eAfE-7985dCe414D9"
            }
          },
          {
            name: "vue3-template",
            entry: environment.production ? "/vue3-dist/" : "//localhost:8081",
            container: "#vue-container",
            activeRule: "#/portal/vue3",
            props: {
              basename: "/portal/vue3"
            }
          }
        ],
        {
          beforeLoad: (app) => {
            console.log("[LifeCycle] before load %c%s", "color: green;", app.name);
            return Promise.resolve();
          },
          beforeMount: (app) => {
            console.log("[LifeCycle] before mount %c%s", "color: green;", app.name);
            return Promise.resolve();
          },
          afterUnmount: (app) => {
            console.log("[LifeCycle] after unmount %c%s", "color: green;", app.name);
            return Promise.resolve();
          }
        }
      );

      addGlobalUncaughtErrorHandler((event: Event | string) => {
        const { message } = event as any;
        if (message && message.includes("died in status LOADING_SOURCE_CODE")) {
          console.error("微应用加载失败，请检查应用是否可运行");
        }
      });

      start({
        prefetch: false,
        urlRerouteOnly: true,
        singular: true,
        sandbox: {
          strictStyleIsolation: true
        }
      });
    }
  }

  toggle() {
    this.isCollapsed = !this.isCollapsed;
  }
}
